package cn.edu.nwafu.hjpg.controller;

import cn.edu.nwafu.hjpg.common.HttpResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("/download")
public class FileController extends HttpServlet {
    @PostMapping(value = "/getWordFile")
    public HttpResult getWordFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = "test.docx";
        response.setContentType("application/msword");//告诉浏览器输出内容为流
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        File file = new File("D:/downloads/" + fileName);
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        OutputStream outputStream = response.getOutputStream();

        int byteread = 0; // 读取的字节数
        try {
            byte[] buffer = new byte[1024];
            while ((byteread = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return HttpResult.ok("200");
    }

    @PostMapping(value = "/getPdfFile")
    @ResponseBody
    public HttpResult getPdfFile(@RequestParam String type) {

        return HttpResult.ok("getPdfFile");
    }


    @RequestMapping(value = "downloadPDF" ,method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadPDF(int id) throws IOException {
        Path path = Paths.get("src\\main\\resources\\doc\\设计文档.pdf");
        byte[] contents = Files.readAllBytes(path);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        String fileName = "output.pdf";
        headers.add("content-disposition", "inline;filename=" + fileName);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
        return response;



    }
}
